import React, { memo, useContext } from 'react'
import { ContentWrap } from './style'
import { Tabs } from 'antd'
import SplitBtn from '../SplitBtn';
import { splitContext } from '../SplitContextProvider'
type TargetKey = React.MouseEvent | React.KeyboardEvent | string;

const Content = memo(() => {
  const {
    tabItems,
    setTabItems,
    tabActiveKey,
    setTabActiveKey,
    setTreeSeletedKeys
  } = useContext(splitContext);

  const onChange = (key: string) => {
    setTabActiveKey(key);
    setTreeSeletedKeys([key]);
  };

  // 删除Tab
  const remove = (targetKey: TargetKey) => {
    const targetIndex = tabItems.findIndex((pane: any) => pane.key === targetKey);
    const newPanes = tabItems.filter((pane: any) => pane.key !== targetKey);
    if (newPanes.length && targetKey === tabActiveKey) {
      const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex];
      setTabActiveKey(key);
      setTreeSeletedKeys([key]);
    }
    setTabItems(newPanes);
  };

  const onEdit = (targetKey: TargetKey, action: 'add' | 'remove') => {
    if (action === 'remove') {
      remove(targetKey)
    }
  };

  return (
    <ContentWrap>
      <Tabs
        hideAdd
        onChange={onChange}
        items={tabItems}
        type="editable-card"
        activeKey={tabActiveKey}
        onEdit={onEdit}
        tabBarExtraContent={<SplitBtn />}
      />
    </ContentWrap>
  )
})

export default Content